from minio import Minio
import os
from concurrent.futures import ThreadPoolExecutor, as_completed
from loguru import logger
import yaml
import shutil


def load_config():
    with open("config.yaml", "r", encoding='utf-8') as file:
        return yaml.safe_load(file)


CONFIG = load_config()


class MinIOClient:
    _instance = None

    def __init__(self):
        config = CONFIG["minio"]
        self.client = Minio(
            config["endpoint"],
            access_key=config["access_key"],
            secret_key=config["secret_key"],
            secure=config["secure"]
        )

    def __new__(cls):
        if not cls._instance:
            cls._instance = super().__new__(cls)
            cls._instance.__init__()
        return cls._instance


# 新增功能函数（添加在FolderSyncer类中）
class FolderSyncer:
    # ... 原有其他代码保持不变 ...

    def print_bucket_files(self, prefix):
        """打印MinIO存储桶指定路径下的文件名（当前层级）"""
        logger.info(f"📂 正在列出MinIO路径 [{prefix}] 下的文件：")
        try:
            objects = self.client.list_objects(
                self.bucket,
                prefix=prefix,
                recursive=False  # 关键参数，不递归
            )

            file_count = 0
            for obj in objects:
                # 过滤掉目录对象
                if not obj.is_dir:
                    # 提取纯文件名（去掉前缀）
                    file_name = obj.object_name[len(prefix):].strip("/")
                    # 过滤子目录（只显示当前层级）
                    if "/" not in file_name:
                        logger.info(f"  - [MinIO] {file_name}")
                        file_count += 1

            logger.success(f"共找到 {file_count} 个文件")

        except Exception as e:
            logger.error(f"列出MinIO文件失败: {str(e)}")

    def print_local_files(self, local_path):
        """打印本地指定路径下的文件名"""
        logger.info(f"📁 正在列出本地路径 [{local_path}] 下的文件：")
        try:
            if not os.path.exists(local_path):
                raise FileNotFoundError("路径不存在")

            if not os.path.isdir(local_path):
                raise NotADirectoryError("不是有效目录")

            file_count = 0
            for item in os.listdir(local_path):
                full_path = os.path.join(local_path, item)
                if os.path.isfile(full_path):
                    logger.info(f"  - [本地] {item}")
                    file_count += 1

            logger.success(f"共找到 {file_count} 个文件")

        except Exception as e:
            logger.error(f"列出本地文件失败: {str(e)}")


# 修改主程序调用
if __name__ == "__main__":
    syncer = FolderSyncer()

    # 示例用法：
    try:
        # 打印MinIO文件（参数为存储桶路径）
        syncer.print_bucket_files("zuoyebang-SQ-3/")

        # 打印本地文件（参数为本地路径）
        syncer.print_local_files("D:/zyb-v3/zuoyebang-SQ-3/")

    except Exception as e:
        logger.critical(f"操作失败: {str(e)}")
        raise
